package cluster

import (
	"context"
	pool "github.com/jolestar/go-commons-pool/v2"
	"go-redis/config"
	"go-redis/database"
	databaseface "go-redis/interface/database"
	"go-redis/interface/resp"
	"go-redis/lib/consistenthash"
)

//CmdFunc 定义集群层的命令的处理函数
type CmdFunc func(cluster *ClusterDatabase, c resp.Connection, cmdArgs [][]byte) resp.Reply

//ClusterDatabase 集群数据库的定义
type ClusterDatabase struct {
	self           string                      // 当前实例的地址
	nodes          []string                    // 集群中其他节点的地址
	peerPicker     *consistenthash.NodeMapping // 集群节点选择hash环的一致性hash地址
	peerConnection map[string]*pool.ObjectPool // 连接池的地址
	db             databaseface.Database       // 集群关联的数据库
}

//NewClusterDatabase 初始化集群的数据库
func NewClusterDatabase() *ClusterDatabase {
	cluster := &ClusterDatabase{
		self:           config.Properties.Self,
		peerPicker:     consistenthash.NewNodeMapping(nil),
		db:             database.NewStandaloneDatabase(),
		peerConnection: make(map[string]*pool.ObjectPool),
	}

	// 加一，表示包含自己的当前实例
	nodes := make([]string, len(config.Properties.Peers)+1)
	for _, peer := range config.Properties.Peers {
		nodes = append(nodes, peer)
	}
	// 将当前实例自己也加入到nodes的节点中
	nodes = append(nodes, config.Properties.Self)
	// 初始化集群的节点
	cluster.nodes = nodes
	// 初始化集群的连接池
	ctx := context.Background()
	for _, peer := range config.Properties.Peers {
		objectPool := pool.NewObjectPoolWithDefaultConfig(ctx, &ConnectionFactory{
			Peer: peer,
		})
		cluster.peerConnection[peer] = objectPool
	}
	return cluster
}

func (cluster *ClusterDatabase) Exec(conn resp.Connection, args [][]byte) resp.Reply {
	//TODO implement me
	panic("implement me")
}

func (cluster *ClusterDatabase) AfterClientClose(conn resp.Connection) {
	//TODO implement me
	panic("implement me")
}

func (cluster *ClusterDatabase) Close() {
	//TODO implement me
	panic("implement me")
}
